package com.cloud.sample.config;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.rm.datasource.SeataDataSourceProxy;
import io.seata.spring.annotation.datasource.SeataDataSourceBeanPostProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(SeataDataSourceProxy.class)
public class SeataConfig {
    @Value("${spring.datasource.dynamic.datasource.mysql.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.dynamic.datasource.mysql.url}")
    private String jdbUrl;

    @Value("${spring.datasource.dynamic.datasource.mysql.username}")
    private String username;

    @Value("${spring.datasource.dynamic.datasource.mysql.password}")
    private String password;

    @Value("${spring.datasource.dynamic.datasource.mysql.hikari.minimum-idle:1}")
    private int minimumIdle;

    @Value("${spring.datasource.dynamic.datasource.mysql.hikari.maximum-pool-size:10}")
    private int maximumPoolSize;

    @Bean
    public DataSourceProxy dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setJdbcUrl(jdbUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMinimumIdle(minimumIdle);
        dataSource.setMaximumPoolSize(maximumPoolSize);
        DataSourceProxy dataSourceProxy = new DataSourceProxy(dataSource);
        return dataSourceProxy;
    }

    @Bean
    public DataSourceBeanPostProcessor dataSourceBeanPostProcessor() {
        return new DataSourceBeanPostProcessor(new String[] {}, "AT");
    }

    class DataSourceBeanPostProcessor extends SeataDataSourceBeanPostProcessor {
        public DataSourceBeanPostProcessor(String[] excludes, String dataSourceProxyMode) {
            super(excludes, dataSourceProxyMode);
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            super.postProcessAfterInitialization(bean, beanName);
            return bean;
        }
    }
}
